/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.learn.learn_view.command;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.ui.rich.learn.learn_view.ExtensionFileFilter;
import br.ufmg.dees.insane.ui.rich.learn.learn_view.LearnInterface;

/**
 * This class is an implementation of the interface Command.
 * its unabled to undo or redo.
 * its "execute" method encodes the current drawing image as
 * a JPEG image in a given file.
 *
 * @author Fonseca, Flavio & Pitangueira, Roque
 * @see gui.command.Command
 */
public class ExportJPEGCommand implements Command {
    
    private LearnInterface parent;
    private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter(new String[]{"jpg", "jpeg"}, "JPEG Files");
	private boolean validFile;
    
//*****************************************************************************
	
    /**
     * Creates new ExportJPEGCommand
     * and sets the FileFilter of FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public ExportJPEGCommand(JFrame parent) {
        this.parent = (LearnInterface)parent;
        fileChooser.setFileFilter(filter);
    }
    
//*****************************************************************************
	
    /**
     * Calls the file chooser an encode the drawing as a JPEG image.
     *
     * @see gui.command.Command#execute()
     */
    public void execute() {
		
		validFile = false;
		while (!validFile) {
			
			fileChooser.setDialogTitle("Export JPEG");
			int retVal = fileChooser.showDialog(parent, "Export");
			if (retVal == JFileChooser.APPROVE_OPTION) {
				//Getting the file name
				String s = fileChooser.getSelectedFile().getName();
				//Getting the file extension
				String ext = new String();
				int i = s.lastIndexOf('.');
				if (i > 0 &&  i < s.length() - 1) {
					ext = s.substring(i+1).toLowerCase();
				}
				//Comparing the extension
				if (!ext.equals("jpg") && !ext.equals("jpeg")){
					s = s + ".jpg";
					File file = fileChooser.getSelectedFile();
					//Changing the file in case of no good extensions
					fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
				}
				
				//Checks if the file exists
				if (fileChooser.getSelectedFile().exists()){
					int value = 10;
					value = JOptionPane.showConfirmDialog(parent, 
					"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
					"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
					if (value == JOptionPane.YES_OPTION){
						validFile = true;
					}
				}
				else {
					validFile = true;
				}
			}
			else return;
		}
        
		Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
		ImageWriter writer = (ImageWriter)writers.next();
		
		try{
			ImageOutputStream ios = ImageIO.createImageOutputStream(fileChooser.getSelectedFile());
			writer.setOutput(ios);
			//getting and writing the buffered image in the output stream
			writer.write(parent.getView().getDrawingArea().getImage());
			parent.addOutputText("File \"" + fileChooser.getSelectedFile().getPath() + "\" successfully exported.");
		} catch (IllegalArgumentException e) {
			System.out.println("One of the arguments to write image is null");
			e.printStackTrace();
		} catch (IOException ie) {
			System.out.println("Exception occured in I/O");
			ie.printStackTrace();
		}
		
    }
    
//*****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//*****************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//*****************************************************************************
}

